import { z } from "zod";
import { arrayToCSV, autoFormatValue } from '../../../tools/str.js';
import { prisma } from '../../../service/mysql.js';
import { TaskType, TaskStatus } from '../type.js';

export default {
    api: "queryDetails",
    name: "查询计划任务明细",
    description: "根据客户的要求查询计划任务明细，比如：查询任务列表。",
    requestSchema: z.object({
        question: z.string().describe("任务查询的查询请求，尽可能保留客户的原话"),
    }),
    func: async ({ question }, context) => {
        const tableSchema = {
            table_id: 't_schedule_task',
            table_desc: '任务明细表',
            columns: [
                { col_name: 'id', col_caption: `任务ID` },
                { col_name: 'task_type', col_caption: `任务类型，可选[${Object.values(TaskType).join('、')}]` },
                { col_name: 'content', col_caption: '任务内容' },
                { col_name: 'cron_expression', col_caption: '任务执行cron表达式' },
                { col_name: 'create_time', col_caption: '任务创建时间，格式：yyyy-mm-dd HH:mm:ss' }
            ]
        }
        const tableData = await prisma.t_schedule_task.findMany({
            where: {
                status: TaskStatus.VALID,
                book_id: context.book.id,
                create_account_no: context.user.id
            },
            orderBy: {
                id: 'desc'
            }
        });
        const formatTableData = tableData.map(row => {
            const processRow = {};
            tableSchema.columns.forEach(column => {
                processRow[column.col_caption] = autoFormatValue(row[column.col_name]);
            });
            return processRow;
        });
        return arrayToCSV(formatTableData);
    }
}